package com.elai.tags.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.elai.common.constant.HttpStatus;
import com.elai.common.constant.ThirdInterface;
import com.elai.common.core.text.Convert;
import com.elai.common.utils.DateUtils;
import com.elai.common.utils.ThirdProperties;
import com.elai.common.utils.WebUtils;
import com.elai.common.utils.sql.SqlTableUtil;
import com.elai.tags.domain.*;
import com.elai.tags.service.BaseUserTagsService;
import com.elai.tags.service.IBaseUserPortraitCompentsService;
import org.apache.commons.collections.ArrayStack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.elai.common.annotation.Log;
import com.elai.common.core.controller.BaseController;
import com.elai.common.core.domain.AjaxResult;
import com.elai.common.enums.BusinessType;
import com.elai.tags.service.IBaseUserPortraitService;
import com.elai.common.utils.poi.ExcelUtil;
import com.elai.common.core.page.TableDataInfo;

/**
 * 用户分群Controller
 *
 * @author elai
 * @date 2021-10-09
 */
@RestController
@RequestMapping("/user/portrait")
public class BaseUserPortraitController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(BaseUserPortraitController.class);
    @Autowired
    private IBaseUserPortraitService baseUserPortraitService;

    @Autowired
    private ThirdProperties thirdProperties;

    @Autowired
    private BaseUserTagsService baseUserTagsService;

    @Autowired
    private IBaseUserPortraitCompentsService baseUserPortraitCompentsService;

    /**
     * 查询用户分群列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BaseUserPortrait baseUserPortrait)
    {
        startPage();
        List<BaseUserPortrait> list = baseUserPortraitService.selectBaseUserPortraitList(baseUserPortrait);
        return getDataTable(list);
    }

    @GetMapping("/getAllTagPortraitList")
    public AjaxResult getAllTagPortraitList()
    {
        List<Map> result=new ArrayList<>();
        Map tagsMap=new HashMap();
        tagsMap.put("label","用户标签");
        List<BaseUserTagsDO> list =baseUserTagsService.selectBaseUserTagsList(new BaseUserTagsDO());
        List<Map> tlist=new ArrayList<>();
        list.stream().forEach(t->{
            Map tag=new HashMap();
            tag.put("label",t.getDisplayName());
            tag.put("value",t.getName());
            tlist.add(tag);
        });
        tagsMap.put("options",tlist);
        List<BaseUserPortrait>  tagList= baseUserPortraitService.selectBaseUserPortraitList(new BaseUserPortrait());
        Map portraitMap=new HashMap();
        portraitMap.put("label","用户画像");
        List<Map> plist=new ArrayList<>();
        tagList.stream().forEach(t->{
            Map tag=new HashMap();
            tag.put("label",t.getDisplayName());
            tag.put("value",t.getName());
            plist.add(tag);
        });
        portraitMap.put("options",plist);
        result.add(tagsMap);
        result.add(portraitMap);
        return AjaxResult.success(result);
    }

    /**
     * 导出用户分群列表
     */
    @Log(title = "用户分群", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BaseUserPortrait baseUserPortrait)
    {
        List<BaseUserPortrait> list = baseUserPortraitService.selectBaseUserPortraitList(baseUserPortrait);
        ExcelUtil<BaseUserPortrait> util = new ExcelUtil<BaseUserPortrait>(BaseUserPortrait.class);
        return util.exportExcel(list, "用户分群数据");
    }

    /**
     * 获取用户分群详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        BaseUserPortrait protrait=baseUserPortraitService.selectBaseUserPortraitById(id.intValue());
        BaseUserPortraitCompents param=new BaseUserPortraitCompents();
        param.setPortraitId(id);
        List<BaseUserPortraitCompents>  compentsList= baseUserPortraitCompentsService.selectBaseUserPortraitCompentsList(param);
        protrait.setPortraitTemplateItems(compentsList);
        return AjaxResult.success(protrait);
    }

    /**
     * 新增用户分群
     */
    @Log(title = "用户分群", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BaseUserPortrait baseUserPortrait)
    {
        return toAjax(baseUserPortraitService.insertBaseUserPortrait(baseUserPortrait));
    }

    /**
     * 修改用户分群
     */
    @Log(title = "用户分群", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BaseUserPortrait baseUserPortrait)
    {
        return toAjax(baseUserPortraitService.updateBaseUserPortrait(baseUserPortrait));
    }

    /**
     * 删除用户分群
     */
    @Log(title = "用户分群", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(baseUserPortraitService.deleteBaseUserPortraitByIds(ids));
    }

    @GetMapping("/userPortraitList")
    public TableDataInfo userPortraitList(BaseUserPortrait baseUserPortrait)
    {
        startPage();
//        List<Map> list = new ArrayList();
//        Map data1=new HashMap();
//        data1.put("name","高流失风险用户");
//        data1.put("creator","总部管理员");
//        data1.put("createTime","2021-07-01 21:18:20");
//        list.add(data1);
//
//        Map data2=new HashMap();
//        data2.put("name","过去30天高消费用户");
//        data2.put("creator","总部管理员");
//        data2.put("createTime","2021-07-01 21:18:20");
//        list.add(data2);
        List<BaseUserPortrait> list=baseUserPortraitService.selectBaseUserPortraitList(baseUserPortrait);

        return getDataTable(list);
    }

    @Log(title = "添加用户画像", businessType = BusinessType.INSERT)
    @PostMapping("/addUserProtrait")
    public AjaxResult addUserProtrait(@RequestBody String requestJson)throws Exception{
        logger.info(requestJson);
        JSONObject jsonObj=JSONObject.parseObject(requestJson);
        JSONObject object=jsonObj.getJSONObject("requestJson");
        BaseUserPortrait groupdo=JSONObject.parseObject(object.toJSONString(),BaseUserPortrait.class);
        String tableName= SqlTableUtil.getDrawName();
        groupdo.setName(tableName);
        groupdo.setPortraitRule(object.toJSONString());
        object.put("tableId",groupdo.getName());
        object.put("tableType","ADD");
        JSONObject obj= WebUtils.postCkObj(thirdProperties.getCkUrl(), ThirdInterface.create_portrait_users,object);
        if (obj == null || obj.getInteger("code") != HttpStatus.CK_SUCCESS){
            AjaxResult.error(obj.getString("msg"));
        }
        Long num= Convert.toLong(obj.getString("data"));
        groupdo.setResultTime(DateUtils.getNowDate());
        groupdo.setResultNum(num);
        groupdo.setUpdateTime(DateUtils.getNowDate());
        baseUserPortraitService.insertBaseUserPortrait(groupdo);

        addTaskDetail(groupdo,num);
        String executorParam="url: "+thirdProperties.getLocalUrl()+ThirdInterface.groupXxJobTask+"/"+groupdo.getName()+"\n" +
                "method: get";
        JSONObject requestInfo = new JSONObject();
        requestInfo.put("jobGroup",1);
        requestInfo.put("scheduleType","CRON");
        requestInfo.put("jobDesc",groupdo.getDisplayName());
        requestInfo.put("executorRouteStrategy","FIRST");
        requestInfo.put("scheduleConf","31 0 0 * * ?");
        requestInfo.put("misfireStrategy","FIRE_ONCE_NOW");
        requestInfo.put("glueType","BEAN");
        requestInfo.put("executorHandler","httpUserGroupJobHandler");
        requestInfo.put("executorBlockStrategy","SERIAL_EXECUTION");
        requestInfo.put("executorTimeout",5);
        requestInfo.put("executorFailRetryCount",1);
        requestInfo.put("author","admin");
        requestInfo.put("alarmEmail","229049640@qq.com");
        requestInfo.put("executorParam",executorParam);
        requestInfo.put("glueRemark",groupdo.getDisplayName()+"定时任务");
      /*  JSONObject response= WebUtils.postCkObj(thirdProperties.getXxjobUrl(),ThirdInterface.createJobInfo,requestInfo);
        if(response.containsKey("code")&&200==response.getIntValue("code")){*/
            return AjaxResult.success();
       /* }else{
            return AjaxResult.error("调用api接口失败！");
        }*/
    }


    @PostMapping("/queryUserProtrait")
    public AjaxResult queryUserProtrait(@RequestBody String requestJson)throws Exception{
        logger.info(requestJson);

        String curTime = DateUtils.getTime();

        JSONObject jsonObj=JSONObject.parseObject(requestJson);
        JSONObject object=jsonObj.getJSONObject("requestJson");
        BaseUserPortrait groupdo=JSONObject.parseObject(object.toJSONString(),BaseUserPortrait.class);
        String tableName= SqlTableUtil.getDrawName();
        groupdo.setName(tableName);
        groupdo.setPortraitRule(object.toJSONString());
        object.put("tableId",groupdo.getName());
        object.put("tableType","QUERY");
//        object.put("controlGroupId","draw_1637891734760_0556");  //临时加上
        JSONObject obj= WebUtils.postCkObj(thirdProperties.getCkUrl(), ThirdInterface.find_predict_users,object);
        if (obj == null || obj.getInteger("code") != HttpStatus.CK_SUCCESS){
            AjaxResult.error(obj.getString("msg"));
        }
        JSONObject dataObj = obj.getJSONObject("data");
        List<BaseUserPortraitCompents>  compentList = new ArrayList<>();
        List<BaseUserPortraitCompents>  controlCompentList = new ArrayList<>();
        JSONArray mainArray = dataObj.getJSONArray("mainItems"); //主画像报表结果
        JSONArray controlArray = dataObj.getJSONArray("controlItems"); //对照组报表结果
        if (!ObjectUtils.isEmpty(mainArray)){
            compentList = mainArray.toJavaList(BaseUserPortraitCompents.class);
        }
        if (!ObjectUtils.isEmpty(controlArray)){
            controlCompentList = controlArray.toJavaList(BaseUserPortraitCompents.class);
        }

//        List<BaseUserPortraitCompents>  compentList=groupdo.getPortraitTemplateItems();
//        initList(compentList);

        Map<String,Object> res = new HashMap<>();
        Map<String,Object> chartData = new HashMap<>();
        chartData.put("mainNum",dataObj.get("mainNum"));
        chartData.put("mainScale",dataObj.get("mainScale"));
        chartData.put("controlNum",dataObj.get("controlNum"));
        chartData.put("controlScale",dataObj.get("controlScale"));
        chartData.put("curTime",curTime);
        res.put("chartData",chartData);
        res.put("chartList",compentList);
        res.put("controlChartList",controlCompentList);

        return AjaxResult.success(res);
    }

    private void initList(List<BaseUserPortraitCompents>  compentList){

        compentList.stream().forEach(citem->{
            if("bar".equals(citem.getChartType())){
                List ydata=new ArrayList();
                ydata.add("衬衫");
                ydata.add("羊毛衫");
                ydata.add("雪纺衫");
                ydata.add("裤子");
                ydata.add("高跟鞋");
                List xdata=new ArrayList();
                Map d1=new HashMap();
                d1.put("name","Search Engine");
                d1.put("value",1048);
                Map d2=new HashMap();
                d2.put("name","Search Engine");
                d2.put("value",1048);
                Map d3=new HashMap();
                d3.put("name","Search Engine");
                d3.put("value",1048);
                Map d4=new HashMap();
                d4.put("name","Search Engine");
                d4.put("value",1048);
                Map d5=new HashMap();
                d5.put("name","Search Engine");
                d5.put("value",1048);
                xdata.add(d1);
                xdata.add(d2);
                xdata.add(d3);
                xdata.add(d4);
                xdata.add(d5);
                citem.setXdata(xdata);
                citem.setYdata(ydata);
            }
            else if("ring".equals(citem.getChartType())){
                List xdata=new ArrayList();
                Map d1=new HashMap();
                d1.put("name","Search Engine");
                d1.put("value",1048);
                Map d2=new HashMap();
                d2.put("name","Search Engine");
                d2.put("value",1048);
                Map d3=new HashMap();
                d3.put("name","Search Engine");
                d3.put("value",1048);
                Map d4=new HashMap();
                d4.put("name","Search Engine");
                d4.put("value",1048);
                Map d5=new HashMap();
                d5.put("name","Search Engine");
                d5.put("value",1048);
                xdata.add(d1);
                xdata.add(d2);
                xdata.add(d3);
                xdata.add(d4);
                xdata.add(d5);
                citem.setXdata(xdata);
            }else if("pie".equals(citem.getChartType())){
                List xdata=new ArrayList();
                Map d1=new HashMap();
                d1.put("name","Search Engine");
                d1.put("value",1048);
                Map d2=new HashMap();
                d2.put("name","Search Engine");
                d2.put("value",1048);
                Map d3=new HashMap();
                d3.put("name","Search Engine");
                d3.put("value",1048);
                Map d4=new HashMap();
                d4.put("name","Search Engine");
                d4.put("value",1048);
                Map d5=new HashMap();
                d5.put("name","Search Engine");
                d5.put("value",1048);
                xdata.add(d1);
                xdata.add(d2);
                xdata.add(d3);
                xdata.add(d4);
                xdata.add(d5);
                citem.setXdata(xdata);
            }
            else if("cate".equals(citem.getChartType())){
                // xdata: ['[20,40]','[40,60]','[60,80]'],
                List xdata=new ArrayList();
                xdata.add(new Integer[]{20,40});
                xdata.add(new Integer[]{40,60});
                xdata.add(new Integer[]{60,80});
                citem.setXdata(xdata);

                List ydata=new ArrayList();
                //ydata: ['张三','李四','王五'],
                ydata.add("张三");
                ydata.add("李四");
                ydata.add("王五");
                citem.setYdata(ydata);

                //data: [[0, 0, 20], [0, 1, 50], [0, 2, 80], [1, 0, 30], [1, 1, 60], [1, 2, 70],[2, 0, 40], [2, 1, 70], [2, 2, 30],]
                List zdata=new ArrayList();
                zdata.add(new Integer[]{0, 0, 20});
                zdata.add(new Integer[]{0, 1, 50});
                zdata.add(new Integer[]{0, 2, 80});
                zdata.add(new Integer[]{1, 0, 30});
                zdata.add(new Integer[]{1, 1, 60});
                zdata.add(new Integer[]{1, 2, 70});
                zdata.add(new Integer[]{2, 0, 40});
                zdata.add(new Integer[]{2, 1, 70});
                zdata.add(new Integer[]{2, 2, 30});
                citem.setZdata(zdata);
            }
            else if("pillar".equals(citem.getChartType())){
                List xdata=new ArrayList();
                Map d1=new HashMap();
                d1.put("name","Search Engine");
                d1.put("value",1048);
                Map d2=new HashMap();
                d2.put("name","Search Engine");
                d2.put("value",1048);
                Map d3=new HashMap();
                d3.put("name","Search Engine");
                d3.put("value",1048);
                Map d4=new HashMap();
                d4.put("name","Search Engine");
                d4.put("value",1048);
                Map d5=new HashMap();
                d5.put("name","Search Engine");
                d5.put("value",1048);
                xdata.add(d1);
                xdata.add(d2);
                xdata.add(d3);
                xdata.add(d4);
                xdata.add(d5);
                citem.setXdata(xdata);
            }
        });
    }

    @Log(title = "预估用户分群数量", businessType = BusinessType.OTHER)
    @PostMapping("/calcUserPortraitNumber")
    public AjaxResult calcUserPortraitNumber(@RequestBody String requestJson){
        logger.info(requestJson);
        logger.info(thirdProperties.getCkUrl());
        JSONObject jsonObj=JSONObject.parseObject(requestJson);
        Map<String, Object> object=jsonObj.getJSONObject("requestJson");
        JSONObject obj= WebUtils.postCkObj(thirdProperties.getCkUrl(), ThirdInterface.find_portrait_count,object);
        if (obj == null || obj.getInteger("code") != HttpStatus.CK_SUCCESS){
            AjaxResult.error(obj.getString("msg"));
        }
        return AjaxResult.success(Convert.toInt(obj.getString("data")));
    }

    @GetMapping(value = "/userPortraitXxjobTask/{name}")
    public AjaxResult userPortraitXxjobTask(@PathVariable("name") String name)
    {
        log.info("分群["+name+"]调度任务开始执行");
        BaseUserPortrait group=new BaseUserPortrait();
        group.setName(name);
        List<BaseUserPortrait> groupList=null;//baseUserTagsService.selectBaseUserTagsList(null);
        if(groupList.size()==1){
            group=groupList.get(0);
            JSONObject object=(JSONObject)JSONObject.toJSON(group);
            object.put("tableId",group.getName());
            object.put("tableType","Task");
            object.put("groupRule",group.getPortraitRule());
            JSONObject obj= WebUtils.postCkObj(thirdProperties.getCkUrl(), ThirdInterface.create_portrait_users,object);
            if (obj == null || obj.getInteger("code") != HttpStatus.CK_SUCCESS){
                AjaxResult.error(obj.getString("msg"));
            }
            Long num= Convert.toLong(obj.getString("data"));
            group.setResultNum(num);
            group.setStatus("01");
            group.setResultTime(DateUtils.getNowDate());
            group.setUpdateTime(DateUtils.getNowDate());
            //baseUserTagsService.updateBaseUserGroup(group);
            addTaskDetail(group, num);
        }
        else{
            AjaxResult.error("分群ID["+name+"]查询数据错误");
        }
        return AjaxResult.success(null);
    }

    private void addTaskDetail(BaseUserPortrait group, Long num) {
        //新添加一条执行记录
        BaseUserGroupTaskDetail detail=new BaseUserGroupTaskDetail();
        detail.setBatchNo(DateUtils.dateTime());
        detail.setGroupId(Long.valueOf(group.getId()+""));
        detail.setGroupCode(group.getName());
        detail.setGroupName(group.getDisplayName());
        detail.setTaskTime(DateUtils.getNowDate());
        detail.setResultNum(num !=null? num.intValue():0);
        detail.setResultTime(DateUtils.getNowDate());
        detail.setTaskStatus("01");
        //baseUserTagsService.insertBaseUserGroupTaskDetail(detail);
    }
}
